/* ==================================================================   
 * Created [2009-4-27 下午11:32:55] by Jon.King 
 * ==================================================================  
 * TSS 
 * ================================================================== 
 * mailTo:jinpujun@hotmail.com
 * Copyright (c) Jon.King, 2009-2012 
 * ================================================================== 
*/

package com.jinhe.tss.core.cachepool.extend.connection;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.log4j.Logger;

import com.jinhe.tss.core.cachepool.Cacheable;
import com.jinhe.tss.core.cachepool.IArithmetic;
import com.jinhe.tss.core.cachepool.TimeWrapper;
import com.jinhe.tss.core.cachepool.extend.connection.datasource._Connection;


/** 
 * <p> ConnectionPoolArithmetic.java </p> 
 * 
 * 数据库连接池算法类。
 * 创建、验证、销毁数据库连接。
 * 
 * @author Jon.King 2007-1-9
 */

public class ConnectionPoolArithmetic implements IArithmetic{
    
    protected Logger log = Logger.getLogger(this.getClass());
  
    public Cacheable create(Long cyclelife){
        Connection conn = _Connection.getInstanse().getConnection();
        return new TimeWrapper(TimeWrapper.createRandomKey("Connection"), conn, cyclelife);
    }

    public boolean isValid(Cacheable o){
        Connection conn = (Connection)o.getValue();
        try {
            return !conn.isClosed();
        } catch (SQLException e) {
            return false;
        } 
    }

    public void destroy(Cacheable o){
        if(o == null) return;
        
        Connection conn = (Connection)o.getValue();
        _Connection.getInstanse().releaseConnection(conn);
        o = null;
    }
}

